<?php

/**
 * Class Weixin_Admin_module
 */
class Weixin_Admin_module extends CI_Module
{
    public $weixin_model;
    public $setting;
    public $sid ;

    public function __construct()
    {
        parent::__construct();
        $this->sid = $GLOBALS['sid'];
        $this->load->model('weixin.weixin_model');
        $this->load->model('expert.Expert_model');
        $this->setting = $this->weixin_model->db_get_setting();
        define('TOKEN',     @$this->setting['token']);
        define('APPID',     @$this->setting['appid']);
        define('APPSECRET', @$this->setting['appsecret']);
        $this->adminid = $this->session->userdata('admin_user_id');
        if(!$this->adminid){
            redirect(site_url('admin/index/login'));
        }
    }

    public function card()
    {
        $page_config['perpage']=30;   //每页条数
        $page_config['part']=2;//当前页前后链接数量
        $page_config['url']='weixin/admin/card';//url
        $page_config['seg']=4;//参数取 index.php之后的段数，默认为3，即index.php/control/function/18 这种形式
        $page_config['nowindex']=$this->uri->segment($page_config['seg']) ? $this->uri->segment($page_config['seg']):1;//当前页
        $page_config['total'] = $this->Expert_model->get_expert_count(array('sid'=>$GLOBALS['sid']));
        $this->load->library('mypageclass');
        $this->mypageclass->initialize($page_config);

        $where = array();
        if($this->session->userdata('_ACCESS_LIST') != 'ALL'){
            $where = array($this->Expert_model->admin_user_table .'.id' => $this->session->userdata('admin_user_id'));
        }
        if($_REQUEST['keywords']){
            $condition_str = htmlspecialchars($_REQUEST['keywords']);
        }
        $expert_array = $this->Expert_model->_list($where,$page_config['perpage'],$page_config['nowindex'],'1', $condition_str );
        $this->data['cards'] = $this->weixin_model->db_get_card_bind($expert_array['list']);
        $this->data['expert'] = $expert_array['list'];

        $this->load->library('QrCode');
        $qrCode = new QrCode();
        $file_dir = APPPATH.'cache/qrcode/';
        dmkdir($file_dir);


        foreach ($this->data['expert'] as $k => $v) {

            $file_name = 'qr_expert'.$v['id'].'.png' ;
            $file = $file_dir.$file_name;
            if(!is_file($file)) {
                $qr_str = URLPRE . 'mobile/member/card/?eid=' . $v['id'] . '&from=singlemessage&isappinstalled=0';
                $qrCode->setText($qr_str);
                $qrCode->setSize(200);
                $qrCode->setPadding(10);
                $qrCode->save($file);
            }
            $qr_img = URLPRE.'application/cache/qrcode/'.$file_name;
            $this->data['expert'][$k]['qr_img'] = $qr_img;

            $ret = $this->Expert_model->_expert_select($v['id']);
            $this->data['expert'][$k]['sub'] = $ret;
            foreach ($ret as $vv) {
                $n = $vv['realname'] ? $vv['realname'] : $vv['name'];
                $u = site_url('expert/admin/edit_expert/'.$vv['id']);
                $this->data['expert'][$k]['sub_string'] .= "<a href='$u'>$n</a>&nbsp;&nbsp;,";
            }

        }
        $this->load->view('admin/card', $this->data);
    }

    public function sharelog()
    {
        $adminid = intval($this->uri->segment(4));
        $this->data['info'] = $this->Expert_model->_expert_info($adminid);
        $page_config['perpage']=50;   //每页条数
        $page_config['part']=2;//当前页前后链接数量
        $page_config['url']='weixin/admin/sharelog/'.$adminid.'/';//url
        $page_config['seg']=5;//参数取 index.php之后的段数，默认为3，即index.php/control/function/18 这种形式
        $page_config['nowindex']=$this->uri->segment($page_config['seg']) ? $this->uri->segment($page_config['seg']):1;//当前页
        $page_config['total'] = $this->Expert_model->get_sharelog_count($adminid);
        $this->load->library('mypageclass');
        $this->mypageclass->initialize($page_config);

        $this->data['list'] = $this->Expert_model->get_sharelog_list($adminid, $page_config['perpage'],$page_config['nowindex'],'1');

        $this->load->view('admin/sharelog', $this->data);
    }

    public function unbind_card()
    {
         if($this->session->userdata('_ACCESS_LIST') != 'ALL'){
             return;
         }
        $id = intval($_GET['id']);
        if($this->weixin_model->db_unbind_card('', $id)){
            $this->success('操作成功', site_url('weixin/admin/card'), TRUE);
        }
    }

    public function getweixin()
    {
        $openid = $_GET['openid'];
        $data = $this->weixin_model->get_user_info($openid);
        $nophoto = "'".site_url('static/public/images/nophoto.jpg')."'";
        return '<img style="vertical-align: middle;margin: 0 10px 0 0;" width="35" onerror="this.error=null;this.src='.$nophoto.'" src="'.$data['headimgurl'].'" />' . $data['nickname'];
    }

    public function setting()
    {
        if(!empty($_POST))
        {
            $data = $_POST['Form'];
            if($this->weixin_model->db_setting($data)){
                $this->success('保存成功', site_url('weixin/admin/setting'), TRUE);
            }
        }
        $this->load->view('admin/setting', array('row' => $this->setting));
    }

    public function cardsetting()
    {
        if(!empty($_POST))
        {
            $data = $_POST['row'];
            if($this->weixin_model->db_setting($data)){
                $this->success('保存成功', site_url('weixin/admin/cardsetting'), TRUE);
            }
        }
        $this->load->view('admin/cardsetting', array('row' => $this->setting));
    }

    public function menu_index()
    {
        $button = $this->weixin_model->get_menus(FALSE);
        $this->load->library('mytreeclass');
        $this->mytreeclass->icon = array('&nbsp;│ ', '&nbsp;├─ ', '&nbsp;└─ ');
        $this->mytreeclass->nbsp = '&nbsp;';
        $this->mytreeclass->init($button);
        $str = "<tr><td class='btn_min'>
                    <div class='operat hidden'>
                        <a class='icon-cog action' href='javascript:;'>处理</a>
                        <div class='menu_select'>
                            <ul>
                                <li><a class='icon-pencil' href='".site_url('weixin/admin/menu_edit?id=$id')."'>编辑</a></li>
                                <li><a class='icon-remove-2 doDel' href='javascript:;' data-uri='".site_url('weixin/admin/menu_del?id=$id')."'>删除</a></li>
                            </ul>
                        </div>
                    </div>
                </td>
                <td>\$displayorder</td>
                <td>\$spacer\$name</td>
                <td>\$type</td>
                <td>\$url</td>
                </tr>";
        $select = $this->mytreeclass->get_tree(0, $str);
        $this->load->view('admin/menu', array(
            'button' => $button,
            'select' => $select
        ));
    }

    public function menu_add()
    {
        if(!empty($_POST))
        {
            $data = $_POST['Form'];
            if(empty($data['name'])){
                $this->error('关键词不能为空', '', TRUE);
            }
            if($data['type'] == 'click'){
                $data['key'] = $data['keyurl'];
                if(empty($data['keyurl'])){
                    $this->error('事件不能为空', '', TRUE);
                }
            }else if($data['type'] == 'view'){
                $data['url'] = $data['keyurl'];
                if(empty($data['keyurl'])){
                    $this->error('链接不能为空', '', TRUE);
                }
            }
            unset($data['keyurl']);

            if($this->weixin_model->db_save_menu($data))
            {
                $this->success('添加成功', site_url('weixin/admin/menu_index'), TRUE);
            }
        }


        $button = $this->weixin_model->get_menus(TRUE);
        $this->load->library('mytreeclass');
        $this->mytreeclass->icon = array('&nbsp;│ ', '&nbsp;├─ ', '&nbsp;└─ ');
        $this->mytreeclass->nbsp = '&nbsp;';
        $this->mytreeclass->init($button);
        $str = "<option value='\$id'>\$spacer\$name</option>";
        $select = $this->mytreeclass->get_tree(0, $str);
        $this->load->view('admin/menu_edit', array(
            'select' => $select
        ));
    }

    public function menu_edit()
    {
        $this->load->library('mytreeclass');
        if(!empty($_POST))
        {
            $data = $_POST['Form'];
            $id = $_POST['id'];
            if(empty($data['name'])){
                $this->error('关键词不能为空', '', TRUE);
            }
            if($data['type'] == 'click'){
                $data['key'] = $data['keyurl'];
                if(empty($data['keyurl'])){
                    $this->error('事件不能为空', '', TRUE);
                }
            }else if($data['type'] == 'view'){
                $data['url'] = $data['keyurl'];
                if(empty($data['keyurl'])){
                    $this->error('链接不能为空', '', TRUE);
                }
            }
            unset($data['keyurl']);

            if($this->weixin_model->db_save_menu($data, $id))
            {
                $this->success('编辑成功', site_url('weixin/admin/menu_index'), TRUE);
            }
        }

        $id = $_GET['id'];
        $row = $this->weixin_model->db_get_menu_by_id($id);


        $button = $this->weixin_model->db_get_general_menu();
 
        foreach ($button as $k => $v){
            $v['selected'] = ($v['id']==$row['parent_id']) ? 'selected':'';
            $array[$k] = $v;
        }

        $this->mytreeclass->init($array);
        $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
        $select = $this->mytreeclass->get_tree(0, $str);




        $this->load->view('admin/menu_edit', array(
            'select' => $select,
            'row' => $row
        ));
    }

    public function menu_del()
    {
        $id = $_GET['id'];
        $affected = $this->weixin_model->db_menu_del($id);
        if($affected){
            $this->success('删除成功', site_url('weixin/admin/menu_index'), TRUE);
        }
    }
    public function menu_clear()
    {
        $affected = $this->weixin_model->db_menu_clear();
        if($affected){
            echo '1';
        }else{
            echo '0';
        }
    }

    public function menu_send()
    {
        $button = $this->weixin_model->db_get_menu(TRUE, 'name,type,key,url');

        $button = array(
            'button' => array_values($button)
        );
        
  
        $ret = $this->weixin_model->send_menu(json_encode_ex($button));


        if(isset($ret['errcode']) && $ret['errcode'] == 0){
            echo '1';
        }else{
            echo $ret['errcode'] . ': ' . $ret['errmsg'];
        }

    }

    /**
     * 高级群发接口
     */
    public function send()
    {
        $user_group = $this->weixin_model->get_user_group();
        $list = $this->weixin_model->db_get_news_list();
        foreach ($list as $k => $row) {
            $list[$k]['rows'] = $this->weixin_model->db_news_row_by_listid($row['id']);
        }

        $groups = array();
        if(is_array($user_group['groups'])){
            foreach ($user_group['groups'] as $k => $v) {
                $groups[$v['id']] = $v;
            }
        }

        $this->load->view('admin/send', array(
            'user_group' => $groups,
            'list' => $list
        ));
    }

    public function new_send()
    {
        if(isset($_REQUEST['list_id'])){
            $list_id = intval($_REQUEST['list_id']);
        }else{
            $list_id = $this->weixin_model->db_news_init_list();
        }

        if(!empty($_POST['row']) && !empty($_POST['list_id']))
        {
            $row = $_POST['row'];
            $this->weixin_model->db_update_news_list($row, $_POST['list_id']);
            $this->success('更新成功！', site_url('weixin/admin/send'), true);
        }

        $list = $this->weixin_model->db_news_row_by_listid($list_id);

        $list_info = $this->weixin_model->db_get_news_list_by_id($list_id);
        $user_group = $this->weixin_model->get_user_group();
        $this->load->view('admin/new_send', array(
            'user_group' => $user_group['groups'],
            'list_id'    => $list_id,
            'list'       => $list,
            'list_info'  => $list_info
        ));
    }

    public function new_send_add()
    {
        if(!isset($_GET['list_id'])) {
            redirect('weixin/admin/send');
        }
        $list_id = intval($_GET['list_id']);

        if(!empty($_POST['row']))
        {
            $row = $_POST['row'];
            if($_POST['id']> 0)
            {
                if($_POST['old_thumb']!=$row['thumb']){
                    $row['thumb_media_id'] = $this->weixin_model->upload_image($row['thumb']);
                }
                if($row['thumb_media_id'] && !is_array($row['thumb_media_id']) ){
                    $this->weixin_model->db_update_news_row($row, $_POST['id']);
                    $this->success('更新成功！', site_url('weixin/admin/new_send/?list_id='.$list_id), true);
                }
                $this->error('更新失败！原因：'.$row['thumb_media_id']['errmsg'], site_url('weixin/admin/new_send_add/?list_id='.$list_id .'&id='.$_POST['id']), true);
            }
            else
            {
                $row['thumb_media_id'] = $this->weixin_model->upload_image($row['thumb']);

                if($row['thumb_media_id'] && !is_array($row['thumb_media_id']) ){
                    $this->weixin_model->db_insert_news_row($row);
                    $this->success('添加成功！', site_url('weixin/admin/new_send/?list_id='.$list_id), true);
                }
                $this->error('添加失败！原因：'.$row['thumb_media_id']['errmsg'], site_url('weixin/admin/new_send_add/?list_id='.$list_id), true);
            }
        }

        $data = array();
        if(!empty($_GET['id'])){
            $data = $this->weixin_model->db_news_row_by_id(intval($_GET['id']));
        }
        $this->load->view('admin/new_send_add', array(
            'list_id'    => $list_id,
            'data'       => $data
        ));
    }

    public function new_send_delete()
    {
        $id = intval($_GET['id']);
        $list_id = intval($_GET['list_id']);
        if($this->weixin_model->db_news_row_delete_by_id($id)){
            $this->success('删除成功！', site_url('weixin/admin/new_send/?list_id='.$list_id), true);
        }
    }

    public function send_list_delete()
    {
        $id = intval($_GET['id']);
        if($this->weixin_model->db_news_list_delete_by_id($id)){
            $this->success('删除成功！', site_url('weixin/admin/send'), true);
        }
    }

    public function send_news(){
        $id = $_GET['id'];
        $this->weixin_model->send_articles($id);
        $ret = $this->weixin_model->do_article_send($id);

        if(true === $ret){
            echo json_encode(array(
                'errcode' => 0,
            ));
        }else{
            echo json_encode($ret);
        }
        exit;
    }
}